package com.base.component.ai.platform.minimax;

import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import com.base.component.ai.platform.ChatCompletionsHandler;
import com.base.component.ai.platform.core.bo.common.ChatCompletionsBO;
import com.base.component.ai.platform.core.bo.resp.ChatcompletionRespBO;
import com.base.component.ai.platform.core.bo.resp.ChatcompletionRespBO.MmChatcompletionV2ChoicesBO;
import com.base.component.ai.platform.core.utils.Utils;
import com.base.core.head.dto.ai.MessageTextDTO;
import com.gitee.magic.context.ConverterEditorUtils;
import com.gitee.magic.core.json.JsonObject;
import com.gitee.magic.framework.base.rest.HttpRequest;
import com.gitee.magic.framework.base.rest.HttpWrapper;

import lombok.extern.slf4j.Slf4j;

/**
 * https://platform.minimaxi.com/document/ChatCompletion%20v2?key=66701d281d57f38758d581d0
 * @author zywei
 *
 */

@ConditionalOnProperty(
		prefix = "base.ai.minimax",
		value = {"apiKey","groupId"})
@Slf4j
@Component
public class MinimaxV2Handler implements ChatCompletionsHandler<MessageTextDTO> {

	private static final String DATA="data: (\\{.*\\})";
	
	@Value("${base.ai.minimax.url:https://api.minimax.chat}")
	private String url;
	@Value("${base.ai.minimax.apiKey}")
	private String apiKey;
	@Value("${base.ai.minimax.groupId}")
	private String groupId;
	
	@Override
	public List<String> getSupportModel() {
		return Arrays.asList(
	    		"abab6.5s-chat",
	    		"abab6.5t-chat",
	    		"abab6.5g-chat",
	    		"abab5.5-chat",
	    		"abab5.5s-chat");
	}

	@Override
	public String execute(ChatCompletionsBO<MessageTextDTO> param) {
		MmChatcompletionV2AO ao=converterToParam(param);
		ao.setStream(false);
		String requestbody=ConverterEditorUtils.converterObject(ao).toString();

		log.info("model:{} agent :{} request: {}",param.getModel(),param.getCode(),requestbody);
		HttpRequest request = new HttpRequest(url+"/v1/text/chatcompletion_v2");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(requestbody);
		HttpWrapper wrapper = new HttpWrapper();
		String content = wrapper.start(request);
		ChatcompletionRespBO v=ConverterEditorUtils.restoreObject(ChatcompletionRespBO.class, new JsonObject(content));
		if(!CollectionUtils.isEmpty(v.getChoices())) {
			for(MmChatcompletionV2ChoicesBO c:v.getChoices()) {
				return c.getMessage().getContent();
			}
		}
		return null;
	}

	@Override
	public void execute(ChatCompletionsBO<MessageTextDTO> param, Consumer<String> process) {
		MmChatcompletionV2AO ao=converterToParam(param);
		ao.setStream(true);
		String requestbody=ConverterEditorUtils.converterObject(ao).toString();

		log.info("model:{} agent :{} request: {}",param.getModel(),param.getCode(),requestbody);
		HttpRequest request = new HttpRequest(url+"/v1/text/chatcompletion_v2");
		request.setHeader(HttpWrapper.AUTHORIZATION, "Bearer " + apiKey);
		request.setHeader(HttpWrapper.CONTENTTYPE, HttpWrapper.CONTENTTYPE_JSON);
		request.setUrlParam("GroupId", groupId);
		request.setBodyContent(requestbody);
		HttpWrapper wrapper = new HttpWrapper();
    	HttpURLConnection connection=wrapper.requestConnect(request);
    	Utils.streamConsumer200(connection, (s)->{
            Matcher matcher = Pattern.compile(DATA).matcher(s);
            while (matcher.find()) {
                String jsonData = matcher.group(1);
                // 现在jsonData包含了"{...}"中的内容，你可以使用JSON库解析它
                ChatcompletionRespBO dto = ConverterEditorUtils.restoreObject(ChatcompletionRespBO.class, new JsonObject(jsonData));
                if(!CollectionUtils.isEmpty(dto.getChoices())) {
        			for(MmChatcompletionV2ChoicesBO c:dto.getChoices()) {
        				if(c.getDelta()!=null) {
        					process.accept(c.getDelta().getContent());
        				}
        				//完整消息
//        				if(c.getMessage()!=null) {
//        					process.accept("getMessage="+c.getMessage().getContent());
//        				}
        			}
        		}
            }
		});
	}

    public MmChatcompletionV2AO converterToParam(ChatCompletionsBO<MessageTextDTO> param) {
		MmChatcompletionV2AO ao=new MmChatcompletionV2AO();
		ao.setModel(param.getModel());
		ao.setTemperature(param.getTemperature());
		ao.setMessages(param.getMessages());
		return ao;
	}

}
